import axios from 'axios'
import reqLoading from './loading.js'
import Notify from './notify.js'
import router from '../router'

// 创建 axios 实例，配置请求基础路径
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'dev' ? '/dev-api' : 'http://124.223.67.137',
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use((config) => {
  const JWTtoken = localStorage.getItem('assets_token_order')
  config.headers.Authorization = JWTtoken

  // loading start
  return config
})
// 相应拦截器
service.interceptors.response.use((res) => {
  switch (res.data.code) {
    case 403:
      router.replace({
        name: 'login'
      })
  }
  // loading stop
  if (res.data.code !== 200) {
    reqLoading.done()
  }
  return res.data
}, (error) => {
  reqLoading.done()
  Notify.danger('请求错误，请刷新重试')
  return Promise.reject(error)
})

export default service
